package com.sk.api.tool;

import com.sk.api.interfaces.AutowireHelper;
import com.sk.api.interfaces.BaseFactory;
import com.sk.api.interfaces.FactoryBuilder;

import java.util.HashMap;
import java.util.Map;

import sun.rmi.runtime.Log;

public class BindTool {

    private static final BindTool BIND_TOOL = new BindTool();

    public static BindTool getInstance() {
        return BIND_TOOL;
    }

    private Map<String, BaseFactory> map;

    public void init(Class... classes) {
        map = new HashMap<>();
        for (Class clazz : classes) {
            loadClass(clazz);
        }
    }

    public void put(String key, BaseFactory factory) {
        map.put(key, factory);
    }

    private void loadClass(Class clazz) {
        loadByClassName(clazz.getName());
    }

    public void loadByClassName(String className) {
        className = className + "$Builder";
        try {
            Class<? extends FactoryBuilder> tarClass = (Class<? extends FactoryBuilder>) Class.forName(className);
            FactoryBuilder factory = tarClass.newInstance();
            factory.buildFactory(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void bind(Object obj) {
        String clazzName = obj.getClass().getName() + "$Autowire";
        try {
            Class<? extends AutowireHelper> clazz = (Class<? extends AutowireHelper>) Class.forName(clazzName);
            AutowireHelper autowire = clazz.newInstance();
            autowire.autowire(obj, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}